package com.jsptpd.smartauth.modules.business.auth;

import com.jsptpd.smartauth.common.util.AppAuthUtils;
import com.jsptpd.smartauth.common.util.IPUtils;
import com.jsptpd.smartauth.common.util.JWTUtil;
import com.jsptpd.smartauth.common.util.StringUtil;
import com.jsptpd.smartauth.modules.business.utils.Constants;

import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//@Component
@WebFilter(filterName = "auth", urlPatterns = "/*")
public class AuthFilter implements Filter {

    @Value("${config.filter.ip}")
    String ipFilter;

    //private Logger log = LoggerFactory.getLogger(AuthFilter.class);
    // 15 days
    //public static int expireMillSecond = 1000 * 60 * 60 * 24 * 15;

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        // TODO Auto-generated method stub

        HttpServletRequest httprequest = (HttpServletRequest) req;

        //简单IP白名单鉴权
        String ipAddr = IPUtils.getRealIP(httprequest);
        if(ipFilter!=null && !ipFilter.isEmpty()){
            List<String> ipList = Arrays.asList(ipFilter.split("\\;"));
            if(ipList.contains(ipAddr)){
                chain.doFilter(req, res);
                return;
            }
        }

        //token相关路径，根目录和cpdat相关的路径不进行权限认证
        if (httprequest.getRequestURI().startsWith("/token")
                || httprequest.getRequestURI().startsWith("/login")
                || httprequest.getRequestURI().startsWith("/bind")
                || httprequest.getRequestURI().startsWith("/verify")
                || httprequest.getRequestURI().startsWith("/webjars")
                || httprequest.getRequestURI().startsWith("/swagger")
                || httprequest.getRequestURI().startsWith("/v2")
                || httprequest.getRequestURI().equals("/")
                || httprequest.getRequestURI().contains("/cpdat")
                || httprequest.getRequestURI().contains("/othertest")
                || httprequest.getRequestURI().contains(".html")) {
            chain.doFilter(req, res);
        } else {
            if(AppAuthUtils.checkAppIdAndKey(httprequest)){
                String tokenId = httprequest.getHeader(Constants.AUTH_HEADTAG_TOKEN);
                tokenId = tokenId.substring(Constants.AUTH_HEADTAG_TOKEN_BEAR.length());
                if (tokenId == null) {
                    ((HttpServletResponse) res).sendError(401);
                } else {
                    String userId = JWTUtil.getAppUID(tokenId);
                    if(StringUtil.isNotEmpty(userId)){
                        chain.doFilter(req, res);
                    }else{
                        ((HttpServletResponse) res).sendError(401);
                    }
                /*if (httprequest.getRequestURI().contains("/cad") || httprequest.getRequestURI().contains("/pcway")|| httprequest.getRequestURI().contains("/publish")) {
                    SimpleDateFormat dateFormater = new SimpleDateFormat("yyyyMMddHH");
                    Date date = new Date();
                    String now = dateFormater.format(date);
                    try {
                        String nowkey = HashHelper.sha1(HashHelper.md5(HashHelper.sha1(now)));
                        if (tokenId.contains(nowkey)) {
                            chain.doFilter(req, res);
                            return;
                        }
                    } catch (Exception ex) {
                    }
                }

                Token token = mapper.selectByPrimaryKey(tokenId);
                if (token == null) {
                    // ((HttpServletResponse) res).setStatus(401);
                    ((HttpServletResponse) res).sendError(401);
                } else {
                    Date currentDate = new Date();
                    if (currentDate.getTime() - token.getTokenCreateDate().getTime() > expireMillSecond) {
                        // ((HttpServletResponse) res).setStatus(401);
                        ((HttpServletResponse) res).sendError(401);
                    } else {
                        chain.doFilter(req, res);
                    }
                }*/

                }
            }else{
                ((HttpServletResponse) res).sendError(401);
            }
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub
    }

}
